<?php
	
	namespace app\api\controller;
	
	
	use app\common\model\Config;
	use app\common\model\Config as ConfigModel;
	use app\common\model\VioContent;
    use app\common\model\VioContentWord;
    use app\common\model\WebsiteCategory;
	use app\common\model\Words;
	use app\common\model\Wordscategory;
	use PhpOffice\PhpWord\PhpWord;
	use think\Db;
	use app\common\controller\Api;

	/**
	 * 首页接口
	 */
	class Index extends Api
	{
		protected $noNeedLogin = ['webinfo'];
		protected $noNeedRight = ['*'];
		
		/**
		 * @Author   : crafters@qq.com
		 * @DateTime : 2022-3-2 11:00
		 * @Introduce: 介绍
		 * @throws \think\Exception
		 */
		public function index()
		{
			
			$vioContentModel = new VioContent;
			
			//网站总数量  ========================================================
			$website_count = Db::name('website')->where(['user_id'=>$this->auth->id])->count();
			
			//当日违规网站数量 ========================================================
			$field                       = "id, main,title, link, category, word, right_word, snapshot, website_lib_id, website_id, created_at";
			$today_illegal_website_count = $vioContentModel
                ->where(['user_id'=>$this->auth->id])
                ->field($field)
                ->whereTime('created_at', 'today')
                ->count();
			
			function operationWordList($word, &$words_list)
			{
				if (!in_array(trim($word), $words_list)) {
					$words_list[$word] = 1;
				} else {
					$words_list[$word] += 1;
				}
			}
			//总和违规关键词个数
			$total      = 0;
			$words_list = [];


			
			//违规网站列表========================================================
			$vioContentList = $vioContentModel->field("id, main, title, from_unixtime(created_at, '%Y-%m-%d %H:%i:%s') as ctime")
                ->where(['user_id'=>$this->auth->id])
                ->order('created_at desc')
                ->paginate(20);
			
			//网站类型========================================================
			$websiteCategoryModel = new WebsiteCategory;
			$website_category     = $websiteCategoryModel->alias('w')
                ->field("id, cate_name, from_unixtime(created_at, '%Y-%m-%d %H:%i:%s') as ctime")
                ->select();
            $websiteModel = new \app\common\model\Website();
            foreach ($website_category as $key => $val){
                $val['website_count'] =$websiteModel->where(['filing_type'=>$val['id'],'user_id'=>$this->auth->id])->count();
            }
			$data = [
				'website_count'                    => $website_count,
				'today_illegal_website_count'      => $today_illegal_website_count,
				'vio_content_list'                 => $vioContentList->items(),
//				'trend_illegal_website_total_list' => $trend_illegal_website,
				'website_category'                 => $website_category,
			];
			
			$this->success('请求成功', $data);
			
		}
		
		public function mingan(){
            $vioContentModel = new VioContent;
            //敏感词级别 ========================================================
            $sensitive = [
                [
                    'level_name' => '一级',
                    'total'      => 0,
                ],
                [
                    'level_name' => '二级',
                    'total'      => 0,
                ],
                [
                    'level_name' => '三级',
                    'total'      => 0,
                ],
                [
                    'level_name' => '四级',
                    'total'      => 0,
                ],
            ];

            $contentwordModel = new VioContentWord();
               for ($i=0;$i<=3;$i++){
                   $wordsids = Db::name('sensitive_words')->where(['level' => $i+1])->column('id');
                   $count = $contentwordModel->where(['user_id'=>$this->auth->id])->whereIn('sensitive_words_id',$wordsids)->count();
                   $sensitive_level[$i]['level_name'] =$sensitive[$i]['level_name'];
                   $sensitive_level[$i]['total'] =$count ? $count: $sensitive[$i]['total'];
               }
//            function operationWordList($word, &$words_list)
//            {
//                if (!in_array(trim($word), $words_list)) {
//                    $words_list[$word] = 1;
//                } else {
//                    $words_list[$word] += 1;
//                }
//            }
//            $field                       = "id, main,title, link, category, word";
//            $vioContent = $vioContentModel->field($field)->select();
//            //总和违规关键词个数
//            $total      = 0;
//            $words_list = [];
//            foreach ($vioContent as $value) {
//                $field_word = trim($value['word']);
//                $words_arr  = explode('|', $field_word);
//                if (count($words_arr) > 0) {
//                    foreach ($words_arr as $word) {
//                        $sensitive_words = Db::name('sensitive_words')->where(['words' => trim($word)])->find();
//                        if ($sensitive_words) {
//                            $total                                                           += 1;
//                            $sensitive_level[intval($sensitive_words['level']) - 1]['total'] += 1;
//                        }
//                        operationWordList($word, $words_list);
//                    }
//                } else {
//                    $sensitive_words = Db::name('sensitive_words')->where(['words' => $field_word])->find();
//                    if ($sensitive_words) {
//                        $total                                                           += 1;
//                        $sensitive_level[intval($sensitive_words['level']) - 1]['total'] += 1;
//                    }
//                    operationWordList($field_word, $words_list);
//                }
//            }
            $this->success('成功', $sensitive_level);
        }
    ///
        public function weigui(){
            $vioContentModel = new VioContent;
            //网站违规趋势========================================================
            for ($i=0;$i<7;$i++){
                $date = date('Y-m-d',time()-(7-$i-2)*24*3600);
                $date1[$i] = strtotime($date);
                $data2[$i] = date('m-d',time()-(7-$i-2)*24*3600);
            }
            $data = [];
            foreach($date1 as $k1 => $v1){
                if(!empty($date1[$k1+1])){
                    $num = $vioContentModel
                        ->where(['user_id'=>$this->auth->id])
                        ->whereBetween("created_at",[$v1,$date1[$k1+1]])
                        ->count();
                    if($num){
                        $data[$k1]['num'] =$num;
                    }else {
                        $data[$k1]['num'] =0;

                    }
                    $data[$k1]['time'] =$data2[$k1];
                }
            }
            $this->success('',$data);
        }

        public function leibie(){
            //违规类别========================================================
            $sensitiveCategoryModel = new Wordscategory;
            $contentwordModel = new VioContentWord();
            $data = $contentwordModel->field('count(*) as num,sensitive_words_category_id as cid')
                ->where(['user_id'=>$this->auth->id])
                ->order('num desc')
                ->group('cid')
                ->select();
            $sensitive_cate_list = [];

           foreach ($data as $key=>$val){
               $cate                  = $sensitiveCategoryModel->where(['id' => $val['cid']])->find();
               $temp                  = [
                   'cate_id'   => $cate['id'],
                   'cate_name' => $cate['cate_name'],
                   'total'     => $val['num'],
               ];
               $sensitive_cate_list[] = $temp;
           }
           $this->success('',$sensitive_cate_list);
        }

		public function export()
		{
			
			if (!$this->request->isGet()) {
				$this->error('请求方法不允许', null, 405);
			}
			
			$this->request->filter(['strip_tags', 'trim']);
			
			$sensitive_words_cate_id = $this->request->param('sensitive_words_cate_id');
			$date_start              = $this->request->param('date_start');
			$date_end                = $this->request->param('date_end');
			
			if (!$date_start || !$date_end) {
				$this->error('导出日期不能为空');
			}
			
			
			$url         = 'http://www.xxx.com/xxx.xlsx';
			$data['url'] = $url;
			$this->success('导出成功', $data);
			
		}
		
		function downFile($sFilePath)
		{
			
			if (file_exists($sFilePath)) {
				
				$aFilePath = explode("/", str_replace("\\", "/", $sFilePath), $sFilePath);
				$sFileName = $aFilePath[count($aFilePath) - 1];
				$nFileSize = filesize($sFilePath);
				header("Content-Disposition: attachment; filename=" . basename($sFileName));
				header("Content-Length:" . $nFileSize);
				header("Content-type: application/octet-stream");
				mb_convert_encoding(readfile($sFilePath), "utf-8", "GB2312");
			}
		}
		
		
		public function test()
		{
			//实例化文档
			$PHPWord = new PhpWord();
			//添加容器
			$section = $PHPWord->addSection();
			//添加图表数据
			$categories = ['A', 'B', 'C', 'D', 'E'];
			$series     = [1, 3, 2, 5, 4];
			//饼图
			$section->addChart('pie', $categories, $series);
			//环图
			$section->addChart('doughnut', $categories, $series);
			//横柱图（字数在上）
			$section->addChart('bar', $categories, $series);
			//横柱图（字数在里）
			$section->addChart('stacked_bar', $categories, $series);
			//横柱图
			$section->addChart('percent_stacked_bar', $categories, $series);
			//竖柱图
			$section->addChart('column', $categories, $series);
			//竖柱图
			$section->addChart('percent_stacked_column', $categories, $series);
			//驼峰图
			$section->addChart('area', $categories, $series);
			//五边形
			$section->addChart('radar', $categories, $series);
			//点图
			$section->addChart('scatter', $categories, $series);
			//线图
			$section->addChart('line', $categories, $series);
			//保存文件后面接文件路径
			$PHPWord->save('chart.docx');
		}
		
		
		/**
		 * @Author   : crafters@qq.com
		 * @DateTime : 2022-3-18 22:18
		 * @Introduce: 网站信息
		 */
		public function webinfo()
		{
			$website_name = ConfigModel::getByName('name');
			$website_logo = ConfigModel::getByName('logo');
			$webinfo = [
				'website_name'=>($website_name && $website_name['value'])?$website_name['value']:'',
				'website_logo'=>($website_logo && $website_logo['value'])?'http://'.$_SERVER['HTTP_HOST'].$website_logo['value']:''
			];
			$this->success('ok', $webinfo);
		}
		
		
	}
